import ttkbootstrap as ttk
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import tkinter.ttk
import os
from Auto import *
from PullPic import *
import openpyxl
import re
def match_number(string_number):#提取返回值的数字
    match = re.search(r':\s*(\d+)', string_number)
    if match:
        string_number_bianhua = match.group(1)
    else:
        string_number_bianhua = 'Not found'
    return string_number_bianhua

# def transfer_images(self):
#     picnum = int(self.NumberSelect.get())
#     save_path = self.PicEntry.get()  # 获取用户输入的路径
#     # save_path = "path/to/save/images"  # 请根据实际情况修改路径
#     self.pullpictopath(picnum, save_path)


def transfer_images(picnum_var, PicEntry):
    # picnum = int(NumberSelect.get())
    picnum = int(picnum_var.get())
    save_path = PicEntry.get()  # 获取用户输入的路径
    if not save_path:
        messagebox.showwarning("警告", "请输入图片保存路径")
        return
    pullpictopath(picnum, save_path)
    messagebox.showinfo("完成", "图片传输已完成！")
class AUTOUI:
    def __init__(self):
        self.frame = ttk.Window()
        self.mainwindow()

    def mainwindow(self):
        Frame_Top = tk.Frame(self.frame)
        Frame_Top.pack(fill=tk.X, expand=True)
        Frame_Top_1 = tk.Frame(Frame_Top)
        Frame_Top_1.pack(fill=tk.X, expand=True)
        tk.Label(Frame_Top_1,text='一键点检工具。').pack(side=tk.LEFT,anchor='w')
        tk.Label(Frame_Top_1, text='Powered By xiangqi.kong').pack(side=tk.RIGHT, anchor='w',padx=20)
        ttk.Separator(Frame_Top, bootstyle=ttk.PRIMARY).pack(fill=tk.X, pady=10)

        Frame_Bottom = tk.Frame(self.frame)
        Frame_Bottom.pack(fill=tk.BOTH, expand=True,padx=5)
        # 设置第0列和第1列的权重为1
        Frame_Bottom.columnconfigure(0, weight=1)
        Frame_Bottom.columnconfigure(1, weight=1)
        Frame_Bottom.columnconfigure(2, weight=1)
        Frame_Bottom.columnconfigure(3, weight=1)
        frame00=ttk.LabelFrame(Frame_Bottom,text='功能设置',bootstyle='info')
        frame00.grid(row=0, column=0, sticky=tk.NSEW, pady=5, padx=5,columnspan=4)
        frame00.grid_size()
        self.mkframe00(frame00)
        frame10 = ttk.LabelFrame(Frame_Bottom, text='AWB参数', bootstyle='info')
        frame10.grid(row=1, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.mkframe10(frame10)
        frame11 = ttk.LabelFrame(Frame_Bottom, text='AE参数', bootstyle='info')
        frame11.grid(row=1, column=1, sticky=tk.NSEW, pady=5, padx=5)
        self.mkframe11(frame11)
        # DP参数
        frame12 = ttk.LabelFrame(Frame_Bottom, text='DP参数', bootstyle='info')
        frame12.grid(row=1, column=2, sticky=tk.NSEW, pady=5, padx=5,columnspan=2,rowspan=2)
        tk.Button(frame12,text='清空信息',command=self.cleartext).pack(anchor='w',padx=10)
        self.DPtext = ttk.ScrolledText(frame12, width=40)
        self.DPtext.pack(fill=tk.X, expand=True, padx=10, pady=10)

        frame20 = ttk.LabelFrame(Frame_Bottom, text='ISP参数', bootstyle='info')
        frame20.grid(row=2, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.mkframe20(frame20)
        frame21 = ttk.LabelFrame(Frame_Bottom, text='三方参数', bootstyle='info')
        frame21.grid(row=2, column=1, sticky=tk.NSEW, pady=5, padx=5)
        self.mkframe21(frame21)

    def mkframe00(self,frame):
        tk.Label(frame,text='DebugParser路径：').grid(row=0, column=0, sticky=tk.NSEW,padx=10,pady=5)
        self.DPEntry =tk.Entry(frame,width=40)
        self.DPEntry.grid(row=0, column=1, sticky=tk.NSEW, padx=10, pady=5, columnspan=3)
        self.DPEntry.insert('0',operatepath())
        tk.Button(frame,text='...',command=self.select_dppath).grid(row=0, column=5, sticky=tk.NSEW,padx=10,pady=5)
        tk.Label(frame, text='项目：').grid(row=0, column=6, sticky=tk.E, padx=10, pady=5)

        self.ProjectSelect = ttk.Combobox(frame, width=20,  state='readonly')
        try:
            project_list = getproject()
            self.ProjectSelect['value'] = project_list
            if project_list != []:
                self.ProjectSelect.current(0)  # 不是空列表的话，显示第一个
        except:
            pass
        self.ProjectSelect.grid(row=0, column=7, sticky=tk.NSEW, padx=10, pady=5, columnspan=2)
        tk.Label(frame,text='图片路径:').grid(row=0, column=10, sticky=tk.NSEW, padx=10, pady=5)
        self.PicEntry=tk.Entry(frame,width=20)
        self.PicEntry.grid(row=0, column=11, sticky=tk.NSEW, padx=10, pady=5, columnspan=2)
        tk.Button(frame,text='...',command=self.open_selection_window).grid(row=0, column=14, sticky=tk.NSEW, padx=10, pady=5)
        tk.Button(frame, text='全局参数刷新').grid(row=1, column=0, sticky=tk.NSEW, padx=10, pady=5)
        tk.Button(frame, text='DP参数',command=self.dp_event).grid(row=1, column=1, sticky=tk.NSEW, padx=10, pady=5)
        tk.Button(frame, text='写入Excel', command=self.write_to_excel).grid(row=1, column=2, sticky=tk.NSEW, padx=10, pady=5)
        style = ttk.Style()
        style.configure('Blue.TLabel', background='#4582EC', foreground='white')
        ttk.Label(frame, text='参数写入选择',style='Blue.TLabel').grid(row=1, column=6, sticky=tk.NSEW, pady=5, padx=5)
        self.CANSHUSensorSelect = ttk.Combobox(frame, width=20, state='readonly',values=['AWB', 'AE'])
        self.CANSHUSensorSelect.grid(row=1, column=7, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.CANSHUSensorSelect.current(0)
        # ttk.Label(frame, text='传入图片张数',style='Blue.TLabel').grid(row=1, column=10, sticky=tk.E, pady=10, padx=5)

        # self.NumberSelect = ttk.Combobox(frame, width=20, state='readonly', values=['1', '5'])
        # self.NumberSelect.grid(row=1, column=11, sticky=tk.E, pady=5, padx=5, columnspan=2)
        # self.NumberSelect.current(0)
        self.picnum_var = tk.StringVar(value="1")
        picnum_options = [str(i) for i in range(1, 11)]  # 可选择 1 到 10 张图片
        self.picnum_menu = tk.OptionMenu(frame, self.picnum_var, *picnum_options)
        self.picnum_menu.config(bg="lightgrey",fg="black",width=20)
        self.picnum_menu.grid(row=1, column=11, sticky=tk.NSEW, padx=10, pady=5)
        tk.Button(frame,text='拉取手机图片',command=lambda: transfer_images(self.picnum_var, self.PicEntry)).grid(row=1, column=10, sticky=tk.E, pady=6, padx=5)

    def mkframe10(self,frame):
        tk.Label(frame,text='摄像头：').grid(row=0, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.AWBSensorSelect = ttk.Combobox(frame, width=20, state='readonly',values=['后摄主','前摄','微距','广角'])
        self.AWBSensorSelect.grid(row=0, column=1, sticky=tk.NSEW, pady=5, padx=5,columnspan=2)
        self.AWBSensorSelect.current(0)
        tk.Label(frame, text='模式：').grid(row=1, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.AWBModeSelect = ttk.Combobox(frame, width=20, state='readonly', values=['AI','Flash','Video'])
        self.AWBModeSelect.grid(row=1, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.AWBModeSelect.current(0)
        tk.Label(frame, text='肤色：').grid(row=2, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.AWBSkinToneSelect = ttk.Combobox(frame, width=20, state='readonly', values=['深肤色', '棕肤色'])
        self.AWBSkinToneSelect.grid(row=2, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.AWBSkinToneSelect.current(0)
    def mkframe11(self,frame):
        tk.Label(frame, text='摄像头：').grid(row=0, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.AESensorSelect = ttk.Combobox(frame, width=20, state='readonly', values=['后摄主', '前摄', '微距', '广角'])
        self.AESensorSelect.grid(row=0, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.AESensorSelect.current(0)
        tk.Label(frame, text='模式：').grid(row=1, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.AEModeSelect = ttk.Combobox(frame, width=20, state='readonly', values=['AI','Flash','Video'])
        self.AEModeSelect.grid(row=1, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.AEModeSelect.current(0)
        tk.Label(frame, text='肤色：').grid(row=2, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.AESkinToneSelect = ttk.Combobox(frame, width=20, state='readonly', values=['深肤色', '棕肤色'])
        self.AESkinToneSelect.grid(row=2, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.AESkinToneSelect.current(0)
    def mkframe20(self,frame):
        tk.Label(frame, text='摄像头：').grid(row=0, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.ISPSensorSelect = ttk.Combobox(frame, width=20, state='readonly', values=['后摄主', '前摄', '微距', '广角'])
        self.ISPSensorSelect.grid(row=0, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.ISPSensorSelect.current(0)
        tk.Label(frame, text='模式：').grid(row=1, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.ISPModeSelect = ttk.Combobox(frame, width=20, state='readonly', values=['AI','Flash','Video'])
        self.ISPModeSelect.grid(row=1, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.ISPModeSelect.current(0)
        tk.Label(frame, text='肤色：').grid(row=2, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.ISPSkinToneSelect = ttk.Combobox(frame, width=20, state='readonly', values=['深肤色', '棕肤色'])
        self.ISPSkinToneSelect.grid(row=2, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.ISPSkinToneSelect.current(0)
    def mkframe21(self,frame):
        tk.Label(frame, text='摄像头：').grid(row=0, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.SSensorSelect = ttk.Combobox(frame, width=20, state='readonly', values=['后摄主', '前摄', '微距', '广角'])
        self.SSensorSelect.grid(row=0, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.SSensorSelect.current(0)
        tk.Label(frame, text='模式：').grid(row=1, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.SModeSelect = ttk.Combobox(frame, width=20, state='readonly', values=['AI','Flash','Video'])
        self.SModeSelect.grid(row=1, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.SModeSelect.current(0)
        tk.Label(frame, text='肤色：').grid(row=2, column=0, sticky=tk.NSEW, pady=5, padx=5)
        self.SSkinToneSelect = ttk.Combobox(frame, width=20, state='readonly', values=['深肤色', '棕肤色'])
        self.SSkinToneSelect.grid(row=2, column=1, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.SSkinToneSelect.current(0)

    def write_to_excel(self):#选择写入AWB还是AE
        info_type = self.CANSHUSensorSelect.get()
        if info_type == "AWB":
            self.write_awb_info()
        elif info_type == "AE":
            self.write_ae_info()

    def write_awb_info(self):
        # 获取用户选择的参数
        dppath = self.DPEntry.get()
        jpgpath = self.PicEntry.get()
        AWBSensorSelect = self.AWBSensorSelect.get()
        AWBModeSelect = self.AWBModeSelect.get()
        AWBSkinToneSelect = self.AWBSkinToneSelect.get()
        content = generate_exif(dppath, jpgpath)
        image_name, awb_tag_date, ae_tag_hw_ver = extract_exif_info(content)
        awb_tag_date_value = match_number(awb_tag_date)

        # 打开Excel文件
        workbook = openpyxl.load_workbook(r"CheckTemplate.xlsx")

        # 根据 AWBSensorSelect 选择相应的 sheet
        sheet_name = AWBSensorSelect  # 根据实际情况确定
        worksheet = workbook[sheet_name]

        def get_actual_value(cell):
            # 如果单元格是合并单元格的一部分，返回合并单元格的值
            for merged_range in worksheet.merged_cells.ranges:
                if cell.coordinate in merged_range:
                    return worksheet.cell(merged_range.min_row, merged_range.min_col).value
            return cell.value

        found = False
        for row in worksheet.iter_rows(min_row=2, values_only=False):  # 假设第一行是标题行
            module = get_actual_value(row[1])  # 模块列
            skin_tone = get_actual_value(row[3])  # 肤色列
            # print(f"Checking row: {row[0].row}, module: {module}, skin_tone: {skin_tone}")
            if module == 'AWB' and skin_tone == AWBSkinToneSelect:
                # 找到匹配的模块和肤色行，继续查找模式行
                for sub_row in worksheet.iter_rows(min_row=row[0].row, max_row=row[0].row + 2,
                                                   values_only=False):  # 从当前行开始，最多遍历三行
                    mode = sub_row[4].value  # 模式列
                    # print(f"Checking sub_row: {sub_row[0].row}, mode: {mode}")

                    if mode == AWBModeSelect:
                        sub_row[5].value = awb_tag_date_value  # 版本号列

                        found = True
                        # print(f"Found matching row: {sub_row[0].row}, mode: {mode}")
                        break
            if found:
                break

        if not found:
            messagebox.showerror(title='错误', message='未找到匹配的行！')
        else:
            # 保存Excel文件
            workbook.save(r"CheckTemplate.xlsx")
            workbook.close()

            # 提示用户已经写入完成
            messagebox.showinfo(title='成功', message='AWB版本号已成功写入Excel！')

    def write_ae_info(self):
        # 获取用户选择的参数
        dppath = self.DPEntry.get()
        jpgpath = self.PicEntry.get()
        AESensorSelect = self.AESensorSelect.get()
        AEModeSelect = self.AEModeSelect.get()
        AESkinToneSelect = self.AESkinToneSelect.get()
        content = generate_exif(dppath, jpgpath)
        image_name, awb_tag_date, ae_tag_hw_ver = extract_exif_info(content)
        ae_tag_hw_ver_value = match_number(ae_tag_hw_ver)

        # 打开Excel文件
        workbook = openpyxl.load_workbook(r"CheckTemplate.xlsx")

        # 根据 AESensorSelect 选择相应的 sheet
        sheet_name = AESensorSelect  # 根据实际情况确定
        worksheet = workbook[sheet_name]

        def get_actual_value(cell):
            # 如果单元格是合并单元格的一部分，返回合并单元格的值
            for merged_range in worksheet.merged_cells.ranges:
                if cell.coordinate in merged_range:
                    return worksheet.cell(merged_range.min_row, merged_range.min_col).value
            return cell.value

        found = False
        for row in worksheet.iter_rows(min_row=2, values_only=False):  # 假设第一行是标题行
            module = get_actual_value(row[1])  # 模块列
            skin_tone = get_actual_value(row[3])  # 肤色列
            # print(f"Checking row: {row[0].row}, module: {module}, skin_tone: {skin_tone}")

            if module == 'AE' and skin_tone == AESkinToneSelect:
                # 找到匹配的模块和肤色行，继续查找模式行
                for sub_row in worksheet.iter_rows(min_row=row[0].row, max_row=row[0].row + 2,
                                                   values_only=False):  # 从当前行开始，最多遍历三行
                    mode = sub_row[4].value  # 模式列
                    # print(f"Checking sub_row: {sub_row[0].row}, mode: {mode}")

                    if mode == AEModeSelect:
                        sub_row[5].value = ae_tag_hw_ver_value  # 版本号列

                        found = True
                        # print(f"Found matching row: {sub_row[0].row}, mode: {mode}")
                        break
            if found:
                break

        if not found:
            messagebox.showerror(title='错误', message='未找到匹配的行！')
        else:
            # 保存Excel文件
            workbook.save(r"CheckTemplate.xlsx")
            workbook.close()

            # 提示用户已经写入完成
            messagebox.showinfo(title='成功', message='AE版本号已成功写入Excel！')

    def cleartext(self):
        self.DPtext.delete(0.0,tk.END)
    def select_dppath(self):
        self.DPEntry.delete(0, tk.END)  # 删除所有值
        file_path1 = filedialog.askopenfilename(filetypes=[('EXE','exe')])  # 使用askopenfilename函数选择单个文件
        self.DPEntry.insert(0,file_path1)
        try:
            operatepath(path=file_path1)
        except:
            return
    # def open_selection_window(self):
    #     selection_window = tk.Toplevel(self.frame)
    #     selection_window.title("选择路径")
    #
    #     def open_file():
    #         file_selected = filedialog.askopenfilename(filetypes=[('JPG', '*.jpg'), ('All Files', '*.*')])
    #         if file_selected:
    #             self.PicEntry.delete(0, tk.END)
    #             self.PicEntry.insert(0, file_selected)
    #         selection_window.destroy()
    #
    #     def open_folder():
    #         folder_selected = filedialog.askdirectory()
    #         if folder_selected:
    #             self.PicEntry.delete(0, tk.END)
    #             self.PicEntry.insert(0, folder_selected)
    #         selection_window.destroy()
    #
    #     tk.Button(selection_window, text="选择文件", command=open_file).pack(pady=10)
    #     tk.Button(selection_window, text="选择文件夹", command=open_folder).pack(pady=10)
    def open_selection_window(self):
        # 弹出文件或文件夹选择对话框
        file_or_folder = messagebox.askquestion("选择操作", "请选择操作类型：\nYes - 选择图片文件\nNo - 选择文件夹",
                                                icon='question')

        if file_or_folder == 'yes':
            # 选择文件
            file_selected = filedialog.askopenfilename(filetypes=[('所有文件', '*.*')])
            if file_selected:
                self.PicEntry.delete(0, tk.END)
                self.PicEntry.insert(0, file_selected)
        else:
            # 选择文件夹
            folder_selected = filedialog.askdirectory()
            if folder_selected:
                self.PicEntry.delete(0, tk.END)
                self.PicEntry.insert(0, folder_selected)

    def dp_event(self):
        dppath =self.DPEntry.get()
        jpgpath = self.PicEntry.get()


        if dppath ==''or jpgpath =='':
            tkinter.messagebox.showerror(title='Error', message='请检查参数是否完整！！！')
        else:
            try:

                content = generate_exif(dppath,jpgpath)
                image_name, awb_tag_date, ae_tag_hw_ver = extract_exif_info(content)
                awb_tag_date_value = match_number(awb_tag_date)
                ae_tag_hw_ver_value = match_number(ae_tag_hw_ver)

                self.textinsert(
                    f"Image Name: {image_name}",
                    f"AWB_TAG_DATE:{awb_tag_date_value if awb_tag_date_value else 'Not found'}",
                    f"AE_TAG_HW_VER:{ae_tag_hw_ver_value if ae_tag_hw_ver_value else 'Not found'}",
                )




            except Exception as e:
                # tkinter.messagebox.showerror(title='Error', message='出错，请重试...')
                tkinter.messagebox.showerror(title='Error', message=f'出错，请重试...详细信息: {str(e)}')

    def textinsert(self, *lines):
        for line in lines:
            self.DPtext.insert('end', line)
            self.DPtext.insert('end', '\n')
        self.DPtext.update_idletasks()




if __name__ == '__main__':

    a = AUTOUI()
    a.frame.mainloop()
